package za.co.johanmynhardt.jsf.converter;

import java.util.logging.Logger;

import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * @author johan.mynhardt@thumbtribe.mobi
 * @version 2011.1219
 */
@ManagedBean
public class StringLengthConverter implements Converter {
	private final Logger logger = Logger.getLogger(StringLengthConverter.class.getName());
	
	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
		return s;
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
		UIParameter paramLength = (UIParameter) uiComponent.findComponent("length");
		int length = 150;
		
		if (paramLength != null) length = Integer.parseInt((String) paramLength.getValue());

		String string = (String) o;
		return string.length() > length ? string.substring(0, length-1).concat("...") : string;
	}
}
